import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'points_mall_logic.dart';
import '../../../gen/assets.gen.dart';

/// 积分商城页面
class PointsMallView extends StatefulWidget {
  const PointsMallView({super.key});

  @override
  State<PointsMallView> createState() => _PointsMallViewState();
}

class _PointsMallViewState extends State<PointsMallView> {
  final controller = Get.find<PointsMallLogic>();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 背景图
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Assets.points.pointsBg.image(
              fit: BoxFit.cover,
              height: 400.h,
            ),
          ),
          // 可滚动内容 - 添加顶部padding避免覆盖固定头部
          Column(
            children: [
              SizedBox(height: 250.h), // 为固定头部留出空间
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      _buildTaskSection(),
                      SizedBox(height: 50.h),
                      _buildMallSection(),
                      SizedBox(height: 40.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
          // 固定的积分头部
          Positioned(
            top: 180.h,
            left: 0,
            right: 0,
            child: IgnorePointer(
              child: _buildPointsHeader(),
            ),
          ),
          // 固定的顶部导航栏
          SafeArea(
            child: _buildAppBar(),
          ),
        ],
      ),
    );
  }

  /// 顶部导航栏
  Widget _buildAppBar() {
    return Container(
      padding:
          EdgeInsets.only(left: 20.w, right: 20.w, top: 20.h, bottom: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
              size: 20.sp,
            ),
          ),
        ],
      ),
    );
  }

  /// 积分头部
  Widget _buildPointsHeader() {
    return Obx(() => Column(
          children: [
            // 积分数值
            Text(
              '${controller.state.points.value}',
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.w500,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 8.h),
            // 活力值文字
            Text(
              '活力值',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.grey[400],
              ),
            ),
          ],
        ));
  }

  /// 任务区块
  Widget _buildTaskSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题和查看其他任务按钮 - 在外面
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '积分任务',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Colors.white,
                ),
              ),
              GestureDetector(
                onTap: controller.toggleOtherTasks,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: const Color(0xFFD9D9D9),
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                  child: Text(
                    '查看其他任务',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(height: 14.h),
        // 任务列表容器
        Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          padding:
              EdgeInsets.only(top: 33.h, bottom: 4.h, left: 20.w, right: 13.w),
          decoration: BoxDecoration(
            color: const Color(0xFF282528),
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Obx(() => Column(
                children: controller.state.taskList.map((task) {
                  return _buildTaskCard(task);
                }).toList(),
              )),
        ),
      ],
    );
  }

  /// 任务卡片
  Widget _buildTaskCard(Map<String, dynamic> task) {
    return Container(
      margin: EdgeInsets.only(bottom: 29.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 30.w,
            height: 30.w,
            decoration: BoxDecoration(
              color: const Color(0xFF353535),
              borderRadius: BorderRadius.circular(50.r),
            ),
            child: Center(
              child: _getTaskIcon(task['icon']),
            ),
          ),
          SizedBox(width: 12.w),
          // 任务信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  task['title'],
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: Colors.white,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  task['subtitle'],
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFFC7C7CC),
                  ),
                ),
                // 如果有进度条
                if (task['progress'] != null) ...[
                  SizedBox(height: 12.h),
                  Stack(
                    clipBehavior: Clip.none,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(4.r),
                              child: LinearProgressIndicator(
                                value: task['progress'] / task['maxProgress'],
                                backgroundColor: Colors.grey[800],
                                valueColor: const AlwaysStoppedAnimation<Color>(
                                  Color(0xFFF46425),
                                ),
                                minHeight: 6.h,
                              ),
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Text(
                            '${task['progress']}',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[400],
                            ),
                          ),
                        ],
                      ),
                      // 金币图标在进度条上方
                      Positioned(
                        left: (task['progress'] / task['maxProgress']) *
                                (MediaQuery.of(Get.context!).size.width -
                                    200.w) -
                            10.w,
                        top: -7.h,
                        child: Assets.points.dollar.image(
                          width: 24.w,
                          height: 24.w,
                        ),
                      ),
                    ],
                  ),
                ],
                // 如果有奖励金币（显示在进度条下方）
                if (task['reward'] != null) ...[
                  SizedBox(height: 8.h),
                  Row(
                    children: [
                      Assets.points.dollar.image(
                        width: 16.w,
                        height: 16.w,
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        '${task['reward']}',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFFFFA726),
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ],
              ],
            ),
          ),
          SizedBox(width: 12.w),
          // 状态按钮
          _buildStatusButton(task),
        ],
      ),
    );
  }

  /// 获取任务图标
  Widget _getTaskIcon(String iconName) {
    AssetGenImage icon;
    switch (iconName) {
      case 'vector':
        icon = Assets.points.vector;
        break;
      case 'complete':
        icon = Assets.points.complete;
        break;
      case 'check_week':
        icon = Assets.points.checkWeek;
        break;
      case 'check_month':
        icon = Assets.points.checkMonth;
        break;
      case 'get':
        icon = Assets.points.get;
        break;
      case 'personal':
        icon = Assets.points.personal;
        break;
      case 'circle':
        icon = Assets.points.circle;
        break;
      case 'create_plan':
        icon = Assets.points.createPlan;
        break;
      default:
        icon = Assets.points.circle;
    }

    return icon.image(
      width: 20.w,
      height: 20.w,
    );
  }

  /// 构建状态按钮
  Widget _buildStatusButton(Map<String, dynamic> task) {
    final status = task['status'];
    Color bgColor;
    Color textColor;
    String text;
    Border? border;

    switch (status) {
      case '去收集':
        bgColor = const Color(0xFF353535);
        textColor = Colors.white;
        text = '去收集';
        border = null;
        break;
      case '收集中':
        bgColor = const Color(0xFF353535);
        textColor = Colors.white;
        text = '收集中';
        border = null;
        break;
      case '已收集':
        bgColor = Colors.transparent;
        textColor = Colors.grey[600]!;
        text = '已收集';
        border = Border.all(
          color: Colors.grey[600]!,
          width: 1,
        );
        break;
      default:
        bgColor = const Color(0xFFBEBEBE);
        textColor = Colors.black;
        text = status;
        border = null;
    }

    return GestureDetector(
      onTap: status == '去收集' ? () => controller.onTaskTap(task) : null,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        decoration: BoxDecoration(
          color: bgColor,
          borderRadius: BorderRadius.circular(20.r),
          border: border,
        ),
        child: Text(
          text,
          style: TextStyle(
            fontSize: 12.sp,
            color: textColor,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  /// 积分商城区块
  Widget _buildMallSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题和地址图标
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '积分商城',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Color(0xfff7f7f7),
                ),
              ),
              Assets.points.location.image(
                width: 24.w,
                height: 24.w,
              ),
            ],
          ),
        ),
        SizedBox(height: 14.h),
        // 商城信息卡片
        Container(
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          padding: EdgeInsets.symmetric(vertical: 22.h, horizontal: 20.w),
          decoration: BoxDecoration(
            color: const Color(0xFF282528),
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Column(
            children: [
              // 消息通知
              Row(
                children: [
                  Container(
                    width: 33.w,
                    height: 33.w,
                    decoration: BoxDecoration(
                      color: const Color(0xFF353535),
                      borderRadius: BorderRadius.circular(50.r),
                    ),
                    child: Center(
                      child: Assets.points.vector.image(
                        width: 20.w,
                        height: 20.w,
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Text(
                      '消息通知...',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 24.h),
              // 分隔线
              Container(
                height: 1,
                color: Color(0xffD9D9D9),
              ),
              SizedBox(height: 15.h),
              // 两个按钮
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: () {
                      Get.toNamed('/points-detail');
                    },
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 33.w,
                          height: 33.w,
                          decoration: BoxDecoration(
                            color: const Color(0xFF353535),
                            borderRadius: BorderRadius.circular(50.r),
                          ),
                          child: Center(
                            child: Assets.points.circle.image(
                              width: 20.w,
                              height: 20.w,
                            ),
                          ),
                        ),
                        SizedBox(width: 12.w),
                        Text(
                          '积分明细',
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Get.toNamed('/exchange-records');
                    },
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 33.w,
                          height: 33.w,
                          decoration: BoxDecoration(
                            color: const Color(0xFF353535),
                            borderRadius: BorderRadius.circular(50.r),
                          ),
                          child: Center(
                            child: Assets.points.gift.image(
                              width: 20.w,
                              height: 20.w,
                            ),
                          ),
                        ),
                        SizedBox(width: 12.w),
                        Text(
                          '兑换记录',
                          style: TextStyle(
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
        SizedBox(height: 28.h),
        // 产品列表区块
        _buildProductListSection(),
      ],
    );
  }

  /// 产品列表区块
  Widget _buildProductListSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
       
        // 产品网格
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Obx(() => Wrap(
                spacing: 15.w,
                runSpacing: 0,
                children: controller.state.productList.map((product) {
                  return _buildProductCard(product);
                }).toList(),
              )),
        ),
      ],
    );
  }

  /// 产品卡片
  Widget _buildProductCard(Map<String, dynamic> product) {
    return GestureDetector(
      onTap: () => controller.onProductTap(product),
      child: Container(
        width: 173.w,
        margin: EdgeInsets.only(bottom: 34.h),
        decoration: BoxDecoration(
          color: const Color(0xFF282528),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 产品图片
            Container(
              width: 173.w,
              height: 173.w,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16.r),
                  topRight: Radius.circular(16.r),
                ),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16.r),
                  topRight: Radius.circular(16.r),
                ),
                child: product['image'] != null
                    ? Image.network(
                        product['image'],
                        fit: BoxFit.cover,
                        width: 173.w,
                        height: 173.w,
                        loadingBuilder: (context, child, loadingProgress) {
                          if (loadingProgress == null) return child;
                          return Container(
                            color: Colors.grey[300],
                            child: Center(
                              child: CircularProgressIndicator(
                                value: loadingProgress.expectedTotalBytes != null
                                    ? loadingProgress.cumulativeBytesLoaded /
                                        loadingProgress.expectedTotalBytes!
                                    : null,
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  Colors.grey[500]!,
                                ),
                              ),
                            ),
                          );
                        },
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            color: Colors.grey[300],
                            child: Center(
                              child: Icon(
                                Icons.broken_image,
                                size: 40.sp,
                                color: Colors.grey[500],
                              ),
                            ),
                          );
                        },
                      )
                    : Container(
                        color: Colors.grey[300],
                        child: Center(
                          child: Icon(
                            Icons.image,
                            size: 40.sp,
                            color: Colors.grey[500],
                          ),
                        ),
                      ),
              ),
            ),
            // 产品信息
            Padding(
              padding: EdgeInsets.all(12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    product['title'],
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 8.h),
                  Row(
                    children: [
                      Text(
                        '${product['points']}积分',
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        '¥${product['price']}',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: const Color(0xFFFF6B35),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
